package meta.api.web.account.presentation;

import java.util.Date;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.code.kaptcha.Constants;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import meta.api.web.account.businessinfo.CaptchaInfo;
import meta.api.web.account.businessinfo.UserInfo;
import meta.api.web.common.util.ApiConst;
import meta.api.web.common.util.ApiUtil;
import meta.common.util.JsonUtil;
import meta.common.util.StrUtil;
import meta.common.util.WebUtil;

@Controller
@RequestMapping(value="api/account")
@Tag(name = "账户管理", description = "账户管理")
public class AccountMngController {

    private static final  String FUNC_NM = "账户管理机能";

    private static final String ERROR_MSG_CODE_ERROR= "验证码错误";
    private static final String ERROR_MSG_CODE_EXPIRED = "验证码已过期";

    /**
     * 图片验证码
     * 
     * @param req 请求
     * @param res 响应
     * @return
     * @throws Exception 异常
     */
    @GetMapping(value="/captcha")
    @Operation(tags = "图片验证码", description = "图片验证码")
    public String captcha(HttpServletRequest req, HttpServletResponse res) throws Exception {
        ApiUtil.callApiLog(req, FUNC_NM, "图片验证码", null);
        ApiUtil.setCaptchaResponse(req, res);
        return null;
    }

    /**
     * 发送邮箱(动态验证码)
     * 
     * @param req 请求
     * @param res 响应
     * @return
     * @throws Exception 异常
     */
    @PostMapping(value="/email")
    @Operation(tags = "发送邮箱(动态验证码)", description = "发送邮箱(动态验证码)")
    public String email(HttpServletRequest req, HttpServletResponse res) throws Exception {
        ApiUtil.callApiLog(req, FUNC_NM, "发送邮箱(动态验证码)", null);

        CaptchaInfo captcha = JsonUtil.toObj(ApiUtil.readTxtBody(req), CaptchaInfo.class);

        if (captcha == null) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_CODE_ERROR);
            return null;
        }

        String reqCode = captcha.getCode();
        if (StrUtil.isEmpty(reqCode)) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_CODE_ERROR);
            return null;
        }

        // get session
        HttpSession session = req.getSession();

        String sesCode = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        Long sesTime = (Long) session.getAttribute(Constants.KAPTCHA_SESSION_DATE);
        if (StrUtil.isEmpty(sesCode) || sesTime == null) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_CODE_EXPIRED);
            return null;
        }

        long intervalSeconds = (System.currentTimeMillis() - sesTime) / 1000;
        if (intervalSeconds > ApiConst.CAPTCHA_EXPIRY_SECONDS) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_CODE_EXPIRED);
            return null;
        }

        if (!reqCode.equalsIgnoreCase(sesCode)) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_CODE_ERROR);
            return null;
        }

        // 生成数字验证码
        String code = ApiUtil.generateNumberCode(6);

        // 验证码用途种类
        String type = captcha.getType();

        // 取得登录用户详细情报
        UserInfo loginUser = WebUtil.getLoginUser(req);
        String username = loginUser != null ? (loginUser.getUsername() + "，") : "";

        // 发送邮箱(动态验证码)
        ApiUtil.sendCodeToMail(username, code, captcha.getEmail(), type);

        if (ApiConst.EMAIL_CODE_TYPE_SIGNUP.equals(type)) {
            session.setAttribute(ApiConst.SESSION_DYNAMIC_CODE_VALUE_SIGNUP, code);
            session.setAttribute(ApiConst.SESSION_DYNAMIC_CODE_DATE_SIGNUP, System.currentTimeMillis());
        } else if (ApiConst.EMAIL_CODE_TYPE_FORGET.equals(type)) {
            session.setAttribute(ApiConst.SESSION_DYNAMIC_CODE_VALUE_FORGET, code);
            session.setAttribute(ApiConst.SESSION_DYNAMIC_CODE_DATE_FORGET, System.currentTimeMillis());
        } else if (ApiConst.EMAIL_CODE_TYPE_EMAIL.equals(type)) {
            session.setAttribute(ApiConst.SESSION_DYNAMIC_CODE_VALUE_EMAIL, code);
            session.setAttribute(ApiConst.SESSION_DYNAMIC_CODE_DATE_EMAIL, System.currentTimeMillis());
        }

        session.removeAttribute(Constants.KAPTCHA_SESSION_KEY);
        session.removeAttribute(Constants.KAPTCHA_SESSION_DATE);

        ApiUtil.setEmptyJsonResponse(res);
        return null;
    }
}
